package com.example.rotateimageview.infiniteVp

import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager

class InfiniteAdapter(val datas:List<String>,val views:List<View>,val vp:ViewPager) :PagerAdapter() {

    override fun getCount(): Int {
        return datas.size+2
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        container.addView(views[position % datas.size])
        return views[position % datas.size]
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        super.destroyItem(container, position, `object`)
    }

    override fun finishUpdate(container: ViewGroup) {
        super.finishUpdate(container)
        var position: Int = vp.getCurrentItem()
        if (position == 0) {
            position = datas.size
            vp.setCurrentItem(position, false)
        } else if (position == datas.size + 2 - 1) {
            position = 1
            vp.setCurrentItem(position, false)
        }
    }
}